package com.thinkgem.jeesite.modules.mobile.service;

import com.alibaba.fastjson.JSONObject;
import com.ckfinder.connector.utils.FileUtils;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.ResponseResult;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.I18nUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipment;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipmentLog;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipmentType;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentLogService;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentService;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentTypeService;
import com.thinkgem.jeesite.modules.messages.entity.EleEquipmentMessages;
import com.thinkgem.jeesite.modules.messages.service.EleEquipmentMessagesService;
import com.thinkgem.jeesite.modules.source.entity.EleSource;
import com.thinkgem.jeesite.modules.source.entity.EleSourceGroup;
import com.thinkgem.jeesite.modules.source.entity.EleSourceMultimedia;
import com.thinkgem.jeesite.modules.source.entity.image.EleSourceImage;
import com.thinkgem.jeesite.modules.source.entity.subtitle.EleSourceSubtitle;
import com.thinkgem.jeesite.modules.source.entity.subtitle.EleSourceSubtitleGroup;
import com.thinkgem.jeesite.modules.source.entity.title.EleSourceTitle;
import com.thinkgem.jeesite.modules.source.entity.video.EleSourceVideo;
import com.thinkgem.jeesite.modules.source.service.EleSourceGroupService;
import com.thinkgem.jeesite.modules.source.service.EleSourceMultimediaService;
import com.thinkgem.jeesite.modules.source.service.subtitle.EleSourceSubtitleGroupService;
import com.thinkgem.jeesite.modules.source.service.title.EleSourceTitleService;
import com.thinkgem.jeesite.modules.sys.MessagesUtils;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.SwitchUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.templet.entity.EleTemplet;
import com.thinkgem.jeesite.modules.templet.service.EleTempletService;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author John
 * @Date 2017-06-07
 */
@Controller
@RequestMapping(value = "${adminPath}/mobile")
public class MobileInterFaceService extends BaseController{

    @Autowired
    private SystemService systemService;
    @Autowired
    private EleTempletService eleTempletService;
    @Autowired
    private EleSourceGroupService eleSourceGroupService;
    @Autowired
    private EleEquipmentService eleEquipmentService;

    @Autowired
    private EleEquipmentTypeService eleEquipmentTypeService;
    @Autowired
    private OfficeService officeService;

    @Autowired
    private EleEquipmentMessagesService eleEquipmentMessagesService;

    @Autowired
    private EleEquipmentLogService eleEquipmentLogService;
    @Autowired
	private EleSourceTitleService eleSourceTitleService;
	@Autowired
	private EleSourceSubtitleGroupService eleSourceSubtitleGroupService;
	@Autowired
	private EleSourceMultimediaService eleSourceMultimediaService;
	
	@Autowired
	private EleTempletService templetService;
    @RequestMapping("findpassword")
    @ResponseBody
    public Result find(String username){
        List<User> areaadmins = new ArrayList<>();

        User user = new User();
        user.setName(username);
        List<User> users = systemService.findList(user);

        String result;
        String message;
        if(null == users || users.isEmpty()){
            result = Result.FAILURE;
            String locale = I18nUtils.getLocaleStr();
            message = "用户名或者账号不正确,没有查询到该用户!";
            if(Global.US.equals(locale)){
                message = "The user name or account number is not correct, no query to the user!";
            }
        }
        else if(users.size() >= 2){
            result = Result.FAILURE;
            String locale = I18nUtils.getLocaleStr();
            message = "查询到超过两名用户,请使用手机号查询!";
            if(Global.US.equals(locale)){
                message = "Query to more than two users, please use the phone number query！";
            }

        }
        else{
            result = Result.SUCCESS;
            String locale = I18nUtils.getLocaleStr();
            message = "成功!";
            if(Global.US.equals(locale)){
                message = "Success！";
            }
            User temuser = users.get(0);
            String enname = temuser.getUserType();
            Office company = temuser.getCompany();
            // 区域管理员忘记密码找管理员
            if("2".equals(enname)){
                User admin = systemService.getUser("u_1");
                areaadmins.add(admin);
            }
            else if("1".equals(enname)){
                areaadmins.add(temuser);
            }
            // 其他用户忘记密码找 区域管理员
            else{
                User usera = new User();
                usera.setCompany(company);
                usera.setRole(new Role("2"));
                areaadmins = systemService.findList(usera);
            }
        }

        return new Result(result, message, areaadmins);
    }

    /**
     * 查询用户信息
     * @param token
     * @return
     */
    @RequestMapping(value = "userinfo")
    @ResponseBody
    public Result userinfo(String token){
        User temuser = UserUtils.getByToken(token);

        if(null == temuser.getId()){
            String locale = I18nUtils.getLocaleStr();
            String msg = "用户未登录!";
            if(Global.US.equals(locale)){
                msg = "The user is not logged in!";
            }
            return new Result(Result.NO_LOGIN, msg, null);
        }
        else{
            User admin = UserUtils.getAdminUser();
            JSONObject current = new JSONObject();
            current.put("user", temuser);
            current.put("admin", admin);

            return new Result(Result.SUCCESS, "成功", current);
        }
    }


    /**
     * 修改个人用户密码
     *
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping(value = "modifyPwd")
    @ResponseBody
    public Result modifyPwd(String token, String oldPassword, String newPassword){
        User user = UserUtils.getByToken(token);
        if(null == user.getId()){
            String locale = I18nUtils.getLocaleStr();
            String msg = "用户未登录!";
            if(Global.US.equals(locale)){
                msg = "The user is not logged in!";
            }
            return new Result(Result.NO_LOGIN, msg, null);
        }
        else{
            String result;
            String message;
            if(StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
                if(SystemService.validatePassword(oldPassword, user.getPassword())){
                    systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
                    String locale = I18nUtils.getLocaleStr();
                    message = "修改密码成功!";
                    if(Global.US.equals(locale)){
                        message = "Revise the password successfully!";
                    }

                    result = Result.SUCCESS;
                }
                else{
                    String locale = I18nUtils.getLocaleStr();
                    message = "修改密码失败，旧密码错误!";
                    if(Global.US.equals(locale)){
                        message = " Failed to modify the password, the old password is wrong!";
                    }

                    result = Result.FAILURE;
                }
            }
            else{
                String locale = I18nUtils.getLocaleStr();
                message = "新旧密码不能为空!";
                if(Global.US.equals(locale)){
                    message = " New and old ciphers can't be empty!";
                }

                result = Result.FAILURE;
            }
            return new Result(result, message, null);
        }
    }

    @RequestMapping("equipmentlist")
    @ResponseBody
    public Result list(String token, String mac){
        User current = UserUtils.getByToken(token);
        if(null == current.getId()){
            String locale = I18nUtils.getLocaleStr();
            String msg = "用户未登录!";
            if(Global.US.equals(locale)){
                msg = "The user is not logged in!";
            }
            return new Result(Result.NO_LOGIN, msg, null);
        }
        else{
            EleEquipment eleEquipment = new EleEquipment();
            eleEquipment.setCode(mac);

            List<Office> listTree = new ArrayList<>();
            List<User> resultList = (List<User>)getBranchForUser(token).getData();
            Set<String> ids = new HashSet<String>();
            for(User temuser : resultList){
                String officeId = temuser.getOffice().getId();
                String companyId = temuser.getCompany().getId();
                ids.add(officeId);
                ids.add(companyId);
            }
            List<Office> listOffice = officeService.findList(true);
            Set<String> resultSet = new HashSet<String>();
            for(String oid : ids){
                resultSet.add(oid);
                Office tmp = officeService.get(oid);
                for(int i = 0; i < listOffice.size(); i++){
                    Office item = listOffice.get(i);
                    if(item.getId().equals(tmp.getParentId())){
                        System.out.println(item);
                        tmp = item;
                        i = -1;
                        resultSet.add(item.getId());
                    }
                }
            }
            for(String oid : resultSet){
                Office item = officeService.get(oid);
                item.setAddress(null);
                item.setEmail(null);
                item.setFax(null);
                item.setRemarks(null);
                item.setPhone("display:none;");
                listTree.add(item);
            }
            Set<String> eqIds = new HashSet<>();
            for(User tmp : resultList){
                EleEquipment eleEquipmentTmp = new EleEquipment();
                eleEquipmentTmp.setCompany(tmp.getCompany());
                eleEquipmentTmp.setOffice(tmp.getOffice());

                List<EleEquipment> listEquipment = eleEquipmentService.findList(eleEquipment);
                for(EleEquipment equipment : listEquipment){
                    if(eqIds.contains(equipment.getId())){
                        continue;
                    }
                    eqIds.add(equipment.getId());
                    Office Office = new Office();
                    Office.setId(equipment.getId());
                    Office.setParent(new Office(equipment.getOffice().getId()));
                    Office.setAddress(equipment.getCode());
                    Office.setEmail(equipment.getType().getName());
                    Office.setFax(equipment.getWidth() + " X " + equipment.getHeight());
                    Office.setRemarks(equipment.getRemarks());
                    Office.setPhone("");
                    listTree.add(Office);
                }
            }
            return new Result(listTree);
        }
    }

    @RequestMapping(value = "equipmentType")
    @ResponseBody
    public Result treeData(String token){
        User thisuser = UserUtils.getByToken(token);
        if(null == thisuser.getId()){
            String locale = I18nUtils.getLocaleStr();
            String msg = "用户未登录!";
            if(Global.US.equals(locale)){
                msg = "The user is not logged in!";
            }
            return new Result(Result.NO_LOGIN, msg, null);
        }
        else{
            List<EleEquipmentType> list = eleEquipmentTypeService.findList(new EleEquipmentType());
            return new Result(list);
        }
    }

    /**
     * 上报设备
     *
     * @param code
     * @param company
     * @param office
     * @param type
     * @param width
     * @param height
     * @return
     */
    @RequestMapping(value = "equipmentAdd")
    @ResponseBody
    public Result add(String token, String code, String company, String office, String type, int width, int height){
        User thisuser = UserUtils.getByToken(token);
        if(null == thisuser.getId()){
            String locale = I18nUtils.getLocaleStr();
            String msg = "用户未登录!";
            if(Global.US.equals(locale)){
                msg = "The user is not logged in!";
            }
            return new Result(Result.NO_LOGIN, msg, null);
        }
        else{
            EleEquipment eleEquipment = eleEquipmentService.findEquipmentByCode(code);
            if(null == eleEquipment
                || EleEquipment.DEL_FLAG_DELETE.equals(eleEquipment.getDelFlag())
                || EleEquipment.DEL_FLAG_AUDIT_NO.equals(eleEquipment.getDelFlag())){
                eleEquipment = new EleEquipment();
                eleEquipment.setCode(code);
                if(StringUtils.isEmpty(company)){
                    String locale = I18nUtils.getLocaleStr();
                    String msg = "设备所在分公司不能为空!";
                    if(Global.US.equals(locale)){
                        msg = "The unit where the equipment is located is not empty!";
                    }
                    return new Result(Result.FAILURE, msg, null);
                }
                else{
                    eleEquipment.setCompany(new Office(company));
                }
                if(StringUtils.isEmpty(office)){
                    String locale = I18nUtils.getLocaleStr();
                    String msg = "设备所在分组不能为空!";
                    if(Global.US.equals(locale)){
                        msg = "The unit in which the device is located is not empty!";
                    }
                    return new Result(Result.FAILURE, msg, null);
                }
                else{
                    eleEquipment.setOffice(new Office(office));
                }

                eleEquipment.setType(new EleEquipmentType(type));
                eleEquipment.setWidth(width);
                eleEquipment.setHeight(height);
                eleEquipment.setCreateBy(UserUtils.getUser());
                eleEquipment.setCheckDate(new Date());

                String message;
                // 审核控制没有关闭 并且没有用户权限的时候
                String enname = thisuser.getRole().getEnname();
                if(!("admin".equals(enname) || "areaadmin".equals(enname)) && !SwitchUtils.isClose("equipment:eleEquipment:check")){
                    eleEquipment.setCheckBy(UserUtils.getCheckUser("", thisuser));
                    eleEquipment.setDelFlag(EleEquipment.DEL_FLAG_AUDIT);
                    String locale = I18nUtils.getLocaleStr();
                    message = "设备添加成功,等待区域管理员审核!";
                    if(Global.US.equals(locale)){
                        message = "The equipment is added successfully, waiting for the area administrator to review it!";
                    }

                }
                else{
                    eleEquipment.setCheckBy(thisuser);
                    eleEquipment.setDelFlag(EleEquipment.DEL_FLAG_NORMAL);
                    String locale = I18nUtils.getLocaleStr();
                    message = "设备添加成功!";
                    if(Global.US.equals(locale)){
                        message = "The equipment is added successfully!";
                    }

                }

                try{
                    eleEquipmentService.save(eleEquipment);
                    return new Result(Result.SUCCESS, message, null);
                }
                catch(Exception e){
                    logger.error("保存设备信息失败:", e);
                    return new Result(Result.FAILURE, "", null);
                }
            }
            else if(EleEquipment.DEL_FLAG_AUDIT.equals(eleEquipment.getDelFlag())){
                String locale = I18nUtils.getLocaleStr();
                String message = "设备添加成功,等待审核!";
                if(Global.US.equals(locale)){
                    message = "The equipment is added successfully, waiting to review it!";
                }
                return new Result(Result.FAILURE, message, null);
            }
            else{
                String locale = I18nUtils.getLocaleStr();
                String msg = "设备已经存在!";
                if(Global.US.equals(locale)){
                    msg = "The equipment has already existed!";
                }
                return new Result(Result.FAILURE, msg, null);
            }
        }
    }

    @RequestMapping("templet")
    @ResponseBody
    public Result templet(String token, String remarks, HttpServletRequest request, HttpServletResponse response){
        response.setContentType("application/json; charset=UTF-8");
        User thisuser = UserUtils.getByToken(token);
        if(null == thisuser.getId()){
            String locale = I18nUtils.getLocaleStr();
            String msg = "用户未登录!";
            if(Global.US.equals(locale)){
                msg = "The user is not logged in!";
            }
            return new Result(Result.NO_LOGIN, msg, null);
        }
        else{
            EleTemplet eleTemplet = new EleTemplet();
            eleTemplet.setRemarks(remarks);
            List<User> userList = null;
    		if (thisuser.isAdmin()) {
    			userList = systemService.findAllUsers(thisuser);
    		} else {
    			userList = systemService.findAllUsersInCompany(thisuser);
    			userList.add(UserUtils.getAdminUser());
    		}
    		eleTemplet.setUsers(userList);

    		Page<EleTemplet> page = eleTempletService.findPage(new Page<EleTemplet>(request, response), eleTemplet);

            List<EleTemplet> list = page.getList();
            for(EleTemplet templet:list){
                String templateId = templet.getId();
                String basePath = DictUtils.getDictValue("basePath", "systemvalue", "");
                String zipPath = basePath + "/theme/source/"+templateId+"/"+templateId+".zip";
                templet.setUrl(zipPath);
            }
            page.setList(list);
            return new Result(Result.SUCCESS, "", page);
        }
    }

    @RequestMapping("source")
    @ResponseBody
    public Result source(String token, String remarks, HttpServletRequest request, HttpServletResponse response){
        response.setContentType("application/json; charset=UTF-8");
        User thisuser = UserUtils.getByToken(token);
        if(null == thisuser.getId()){
            String locale = I18nUtils.getLocaleStr();
            String msg = "用户未登录!";
            if(Global.US.equals(locale)){
                msg = "The user is not logged in!";
            }
            return new Result(Result.NO_LOGIN, msg, null);
        }
        else{
            EleSourceGroup sourceGroup = new EleSourceGroup();
            sourceGroup.setVisible("0");
            sourceGroup.setRemarks(remarks);
            List<User> userList = null;
    		if(thisuser.isAdmin()) {
    			userList = systemService.findAllUsers(thisuser);
    		}else {
    			userList = systemService.findAllUsersInCompany(thisuser);
    			userList.add(UserUtils.getAdminUser());		
    		}		
    		sourceGroup.setUsers(userList);
            Page<EleSourceGroup> page = eleSourceGroupService.findPage(new Page<EleSourceGroup>(request, response),
            		sourceGroup);

            List<EleSourceGroup> list = page.getList();
            for(EleSourceGroup source:list){
                String groupId = source.getId();
                String basePath = DictUtils.getDictValue("basePath", "systemvalue", "");
                String zipPath = basePath + "/theme/source/"+groupId+"/"+groupId+".zip";
                source.setUrl(zipPath);
            }
            page.setList(list);
            return new Result(Result.SUCCESS, "", list);
        }
    }

    @RequestMapping("resource")
    @ResponseBody
    public Result resource(String token, String type,String remarks, HttpServletRequest request, HttpServletResponse response){
        response.setContentType("application/json; charset=UTF-8");
        User thisuser = UserUtils.getByToken(token);
        if(null == thisuser.getId()){
            String locale = I18nUtils.getLocaleStr();
            String msg = "用户未登录!";
            if(Global.US.equals(locale)){
                msg = "The user is not logged in!";
            }
            return new Result(Result.NO_LOGIN, msg, null);
        }
        else{
        	List<User> userList = null;
       		if(thisuser.isAdmin()) {
       			userList = systemService.findAllUsers(thisuser);
       		}else {
       			userList = systemService.findAllUsersInCompany(thisuser);
       			userList.add(UserUtils.getAdminUser());		
       		}		
       		List<EleSourceGroup> list = new ArrayList<>();
        	if(!StringUtils.isEmpty(type)){
        		if(type.equals("title")){
        			EleSourceTitle eleSourceTitle = new EleSourceTitle();
        			eleSourceTitle.setUsers(userList);
        			Page<EleSourceTitle> cond = new Page<EleSourceTitle>(request, response);
        			cond.setPageSize(1000000);
        			Page<EleSourceTitle> page = eleSourceTitleService.findPage(cond, eleSourceTitle); 
        			for(EleSourceTitle e:page.getList()) {
        				if(!StringUtils.isEmpty(e.getGroupId())){
        					EleSourceGroup tmp = eleSourceGroupService.getGroupById(e.getGroupId());
        					if(tmp != null){
        						list.add(tmp);
        					}
        				}
        			}
        		}else if(type.equals("subtitle")){
        			EleSourceSubtitleGroup eleSourceSubtitleGroup = new EleSourceSubtitleGroup();
        			eleSourceSubtitleGroup.setUsers(userList);
        			Page<EleSourceSubtitleGroup> cond = new Page<EleSourceSubtitleGroup>(request, response);
        			cond.setPageSize(1000000);
        			Page<EleSourceSubtitleGroup> page = eleSourceSubtitleGroupService.findPage(cond, eleSourceSubtitleGroup); 

        			for(EleSourceSubtitleGroup e:page.getList()) {
        				if(!StringUtils.isEmpty(e.getGroupId())){
        					EleSourceGroup tmp = eleSourceGroupService.getGroupById(e.getGroupId());
        					if(tmp != null){
        						list.add(tmp);
        					}
        				}
        			}
        		}else if(type.equals("multimedia")){
        			EleSourceMultimedia eleSourceMultimedia = new EleSourceMultimedia();
        			eleSourceMultimedia.setUsers(userList);
        			Page<EleSourceMultimedia> cond = new Page<EleSourceMultimedia>(request, response);
        			cond.setPageSize(1000000);
        			Page<EleSourceMultimedia> page = eleSourceMultimediaService.findPage(cond, eleSourceMultimedia); 
        			for(EleSourceMultimedia e:page.getList()) {
        				if(!StringUtils.isEmpty(e.getGroupId())){
        					EleSourceGroup tmp = eleSourceGroupService.getGroupById(e.getGroupId());
        					if(tmp != null){
        						list.add(tmp);
        					}
        				}
        			}
        		}
        			
        	}else{
        		EleSourceGroup sourceGroup = new EleSourceGroup();
        		sourceGroup.setRemarks(remarks);      
        		sourceGroup.setUsers(userList);
        		Page<EleSourceGroup> cond = new Page<EleSourceGroup>(request, response);
    			cond.setPageSize(1000000);
            	Page<EleSourceGroup> page = eleSourceGroupService.findPage(cond,
            		sourceGroup);
            	list = page.getList();
            }
        	 for(EleSourceGroup source:list){
                 String groupId = source.getId();
                 String basePath = DictUtils.getDictValue("basePath", "systemvalue", "");
                 String zipPath = basePath + "/theme/source/"+groupId+"/"+groupId+".zip";
                 source.setUrl(zipPath);
             }
            return new Result(Result.SUCCESS, "", list);
       }
    }
    
    
    @RequestMapping("userbranchuser")
    @ResponseBody
    private Result getBranchForUser(String token){
        User current = UserUtils.getByToken(token);

        if(null == current.getId()){
            String locale = I18nUtils.getLocaleStr();
            String msg = "用户未登录!";
            if(Global.US.equals(locale)){
                msg = "The user is not logged in!";
            }
            return new Result(Result.NO_LOGIN, msg, null);
        }
        else{
            List<User> list = systemService.findList(new User());
            Role role = current.getRole();
            List<User> resultList = new ArrayList<>();
            if(null != role){
                if(current.getUserType().equals("1")){
                    resultList = list;
                }
                else if(current.getUserType().equals("4")){
                    resultList.add(current);
                }
                else if(current.getUserType().equals("3")){
                    for(User usr : list){
                        if(usr.getUserType().equals("4")
                                && usr.getCompany().getId().equals(current.getOffice().getId())){
                            resultList.add(usr);
                        }
                    }
                    resultList.add(current);
                }
                else{
                    Set<String> offices = new HashSet<>();
                    for(User usr : list){
                        if(usr.getUserType().equals("3")
                                && usr.getCompany().getId().equals(current.getOffice().getId())){
                            resultList.add(usr);
                            offices.add(usr.getOffice().getId());
                        }
                    }
                    offices.add(current.getOffice().getId());
                    for(User usr : list){
                        if(usr.getUserType().equals("4") && offices.contains(usr.getCompany().getId())){
                            resultList.add(usr);
                        }
                    }
                    resultList.add(current);
                }
                String locale = I18nUtils.getLocaleStr();
                String msg = "用户未登录!";
                if(Global.US.equals(locale)){
                    msg = "The user is not logged in!";
                }
                return new Result(Result.SUCCESS, msg, resultList);
            }else{
                String locale = I18nUtils.getLocaleStr();
                String msg = "用户角色没有设置,请联系管理员!";
                if(Global.US.equals(locale)){
                    msg = "The user role is not set, please contact the administrator!";
                }
                return new Result(Result.FAILURE, msg, null);
            }
        }
    }

    /**
     * 获取该用户可访问的分公司、分组
     *
     * @param token
     * @return
     */
    @RequestMapping("userbranchoffice")
    @ResponseBody
    private Result userbranchoffice(String token){
        User current = UserUtils.getByToken(token);
        if(null == current.getId()){
            String locale = I18nUtils.getLocaleStr();
            String msg = "用户未登录!";
            if(Global.US.equals(locale)){
                msg = "The user is not logged in!";
            }
            return new Result(Result.NO_LOGIN, msg, null);
        }
        else{
            String userCompanyId = current.getCompany().getId();
            String userOfficeId = current.getOffice().getId();
            List<Office> officeList = officeService.findList(true);
            List<Office> temOfficeList = new ArrayList<>();
            if(!current.isAdmin()){
                for(Office office:officeList){
                    // 公司
                    if("1".equals(office.getType())){
                        if(office.getId().equals(userCompanyId)){
                            temOfficeList.add(office);
                        }
                        else if(office.getParentIds().contains(userCompanyId)){
                            temOfficeList.add(office);
                        }
                    }
                    else if("2".equals(office.getType())){
                        if(office.getId().equals(userOfficeId)){
                            temOfficeList.add(office);
                        }
                        else if(office.getParentIds().contains(userOfficeId)){
                            temOfficeList.add(office);
                        }
                    }
                }
                officeList = temOfficeList;
            }
            return new Result(officeList);
        }
    }

    /**
     * 查询设备连接记录
     * @param id
     * @param mac
     * @param token
     * @return
     */
    @RequestMapping("connectRecord")
    @ResponseBody
    private Result connectRecord(String id, String mac, String token, HttpServletRequest request, HttpServletResponse response){
        User current = UserUtils.getByToken(token);
        if(null == current.getId()){
            String locale = I18nUtils.getLocaleStr();
            String msg = "用户未登录!";
            if(Global.US.equals(locale)){
                msg = "The user is not logged in!";
            }
            return new Result(Result.NO_LOGIN, msg, null);
        }else{
            EleEquipmentMessages condation = new EleEquipmentMessages();
            condation.setId(id);
            condation.setType("connect");
            condation.setMethod("request");
            condation.setMac(mac);

            Page<EleEquipmentMessages> page = eleEquipmentMessagesService.findPage(new Page<EleEquipmentMessages>(request, response), condation);
            return new Result(page);
        }
    }

    /**
     * 上传pad 连接设备的记录
     * @param mac 设备编号
     * @param time 连接时间
     * @param token 用户token
     * @return
     */
    @RequestMapping("reportConnectRecord")
    @ResponseBody
    private Result reportConnectRecord(String mac, Long time, String token){
        User current = UserUtils.getByToken(token);
        if(null == current.getId()){
            String locale = I18nUtils.getLocaleStr();
            String msg = "用户未登录!";
            if(Global.US.equals(locale)){
                msg = "The user is not logged in!";
            }
            return new Result(Result.NO_LOGIN, msg, null);
        }else{
            MessagesUtils.saveMessages("connect", "", "request", ResponseResult.SUCCESS, mac, "设备连接记录", time);
            return new Result(null);
        }
    }

    /**
     * 上报设备日志
     * @param mac
     * @param filename
     * @param file
     * @param token
     * @return
     */
    @RequestMapping(value = "uploadEquipmentLog")
    @ResponseBody
    public Result uploadEquipmentLog(String mac, String filename, MultipartFile file,String token){
        User current = UserUtils.getByToken(token);
        if(null == current.getId()){
            String locale = I18nUtils.getLocaleStr();
            String msg = "用户未登录!";
            if(Global.US.equals(locale)){
                msg = "The user is not logged in!";
            }
            return new Result(Result.NO_LOGIN, msg, null);
        }
        else{
            EleEquipment eleEquipment = eleEquipmentService.findEquipmentConfigByCode(mac);
            String dirPath = Global.getUserfilesBaseDir() + "upload/app/";
            String fullPath = Global.getUserfilesBaseDir() + "upload/app/" + filename;
            String filePath = "upload/app/" + filename;
            if(file != null){
                // 转存文件
                try{
                    File dir = new File(dirPath);
                    if(!dir.exists() && dir.isDirectory()){
                        dir.mkdirs();
                    }
                    File tmp = new File(fullPath);
                    if(tmp.exists()){
                        FileUtils.delete(tmp);
                    }
                    File log = new File(fullPath);
                    file.transferTo(log);
                }
                catch(Exception e){
                    e.printStackTrace();
                }

                EleEquipmentLog log = eleEquipmentLogService.findLogByPath(filePath);
                if(log == null){
                    log = new EleEquipmentLog();
                    log.setEquipmentId(eleEquipment.getId());
                    log.setType("log");
                    log.setPath(filePath);
                    log.setName(filename);
                    eleEquipmentLogService.save(log);
                }
                return new Result(null);
            }
            else{
                return new Result(Result.FAILURE, "", null);
            }
        }
    }
    
    
    @RequestMapping(value = "uploadResource")
    @ResponseBody
    public Result uploadResource(HttpServletRequest request){
    	String token = request.getParameter("token");
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		String data = request.getParameter("data");
		String type = request.getParameter("type");
		List<MultipartFile> file = null;
		logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>1");
		logger.info(data);
		logger.info(type);
		if(isMultipart){
			MultipartHttpServletRequest mmr = (MultipartHttpServletRequest) request;
			file = mmr.getFiles("file");   
			if(file == null){
                String locale = I18nUtils.getLocaleStr();
                String msg = "缺少文件";
                if(Global.US.equals(locale)){
                    msg = "no file";
                }
    			return  new Result(Result.ERROR_PARAM, msg, null);

			}

		}
		 User current = UserUtils.getByToken(token);
	        if(null == current.getId()){
	    		logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>3");
                String locale = I18nUtils.getLocaleStr();
                String msg = "用户未登录!";
                if(Global.US.equals(locale)){
                    msg = "The user is not logged in!";
                }
	            return new Result(Result.NO_LOGIN, msg, null);
	        }
        if(StringUtils.isEmpty(type) || StringUtils.isEmpty(data)) {
    		logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>4");
            String locale = I18nUtils.getLocaleStr();
            String msg = "缺少必要参数!";
            if(Global.US.equals(locale)){
                msg = "Lack of necessary parameters";
            }
        	return  new Result(Result.ERROR_PARAM, msg, null);
        }
        else{
    		logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>5");

            String dirPath = Global.getUserfilesBaseDir().replace("/", "") + "upload/app/"+type;
            System.out.println( Global.getUserfilesBaseDir()+">>>>>>>>>>>>>>>1");
            System.out.println(dirPath+">>>>>>>>>>>>>>>1");

            String contextPath =  "/elevator/upload/app/"+type;
        	if(type.equals("title")) {
        		EleSourceTitle title = (EleSourceTitle) JsonMapper.fromJsonString(data, EleSourceTitle.class);
        		title.setCreateBy(current);
        		saveUploadResource(title);
        	}else if(type.equals("sub")) {
        		EleSourceSubtitleGroup sub = (EleSourceSubtitleGroup) JsonMapper.fromJsonString(data, EleSourceSubtitleGroup.class);
        		for(EleSourceSubtitle es :sub.getEleSourceSubtitleList()) {
        			es.setId("");
        		}
        		System.out.println(sub.getEleSourceSubtitleList().size());
        		String fileName = sub.getBgimage();
        		if(!fileName.startsWith(File.separator)){
        			fileName = "/"+ fileName;
        		}
        		String fullPath = dirPath + fileName;
        		String contextName = contextPath+ fileName;
        		if(file != null && file.size() != 0) {
        			try{
        				MultipartFile bg = file.get(0);
                        File dir = new File(dirPath);
                        if(!dir.exists() && dir.isDirectory()){
                            dir.mkdirs();
                        }
                        File tmp = new File(fullPath);
                        if(tmp.exists()){
                            FileUtils.delete(tmp);
                        }
                        File bgImage = new File(fullPath);
                        bg.transferTo(bgImage);
                    }
                    catch(Exception e){
                        e.printStackTrace();
                    }
        		}
        		sub.setBgimage(contextName);
        		sub.setCreateBy(current);
        		saveUploadResource(sub);
        	}else if(type.equals("multimedia")) {
        		EleSourceMultimedia media = (EleSourceMultimedia) JsonMapper.fromJsonString(data, EleSourceMultimedia.class);
        		dirPath = dirPath+"/"+ media.getType();
        		logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>6");

        		contextPath = contextPath+"/"+ media.getType();
        		if(file.isEmpty()) {
            		logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>7");
                    String locale = I18nUtils.getLocaleStr();
                    String msg = "缺少文件";
                    if(Global.US.equals(locale)){
                        msg = "no file";
                    }
                    return  new Result(Result.ERROR_PARAM, msg, null);

        		}
        		if(media.getType().equals("image")){
            		logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>8");

        			List<EleSourceImage> imageList = media.getImageGroup().getEleSourceImageList();
        			for(EleSourceImage ei:imageList) {
        				ei.setId("");
        				String fileName = ei.getPath();
        				if(!fileName.startsWith(File.separator)){
                			fileName = "/"+ fileName;
                		}
        				String filePath = dirPath+fileName;
        				String contextName = contextPath + fileName;
        				ei.setPath(contextName);
        				for(MultipartFile mf: file) {
        					logger.info(mf.getOriginalFilename());
        					logger.info(filePath);
        					if(filePath.contains(mf.getOriginalFilename())) {
        						createFile(dirPath, filePath, mf);
        					}
        				}
        			}
            		logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>9");

        			media.getImageGroup().setEleSourceImageList(imageList);
         		}else {
         			List<EleSourceVideo> videoList = media.getVideoGroup().getEleSourceVideoList();
        			for(EleSourceVideo ei:videoList) {
        				ei.setId("");
        				if(StringUtils.isEmpty(ei.getLiveUrl())) {
        					String fileName = ei.getPath();
            				if(!fileName.startsWith(File.separator)){
                    			fileName = "/"+ fileName;
                    		}
        					String filePath = dirPath+fileName;
        					String contextName = contextPath +fileName;
            				ei.setPath(contextName);
            				for(MultipartFile mf: file) {
            					if(filePath.contains(mf.getOriginalFilename())) {
            						createFile(dirPath, filePath, mf);
            					}
            				}
        				}
        			}
        			media.getVideoGroup().setEleSourceVideoList(videoList);
         		}
        		media.setCreateBy(current);
        		saveUploadResource(media);
        	}
            String locale = I18nUtils.getLocaleStr();
            String msg = "上传资源成功";
            if(Global.US.equals(locale)){
                msg = "Upload resource success";
            }
            return new Result(Result.SUCCESS,msg,null);

        }
    }
    private void createFile(String dirPath,String fullPath,MultipartFile file) {
    	 try{
             File dir = new File(dirPath);
             if(!dir.exists() && dir.isDirectory()){
                 dir.mkdirs();
             }
             File tmp = new File(fullPath);
             if(tmp.exists()){
                 FileUtils.delete(tmp);
             }
             System.out.println(fullPath);
             File log = new File(fullPath);
             file.transferTo(log);
         }
         catch(Exception e){
             e.printStackTrace();
         }
    }
    public void saveUploadResource(EleSourceTitle eleSourceTitle) {
    	eleSourceTitleService.save(eleSourceTitle);
		
		EleSourceGroup eleSourceGroup = null;
		eleSourceGroup = new EleSourceGroup();
		EleSource source = new EleSource();
		source.setId("");
		source.setType("title");
		source.setName("TitleUpload");
		source.setContent(eleSourceTitle.getId());
			
		List<EleSource> esList = Lists.newArrayList();
		esList.add(source);
		eleSourceGroup.setEleSourceList(esList);
		eleSourceGroup.setVisible("0");
		eleSourceGroup.setType("title");
		
		boolean noNeedCheck = UserUtils.getSubject().isPermitted("source:eleSourceGroup:check")
                || SwitchUtils.isClose("source:eleSourceGroup:check");
		if(noNeedCheck){
			eleSourceGroup.setDelFlag(EleSourceGroup.DEL_FLAG_NORMAL);
		}else{
			eleSourceGroup.setDelFlag(EleSourceGroup.DEL_FLAG_AUDIT);
		}
		eleSourceGroup.setName(eleSourceTitle.getName());

		
		System.out.println(JsonMapper.toJsonString((eleSourceTitle)));

		eleSourceGroupService.save(eleSourceGroup);
		String basePath = Global.getUserfilesBaseDir();
		try {
			templetService.createPackageForSourceGroup(eleSourceGroup, basePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		eleSourceTitleService.updateGroupId(eleSourceGroup.getId(), eleSourceTitle.getId());
	}
	public void saveUploadResource(EleSourceSubtitleGroup eleSourceSubtitleGroup) {
		eleSourceSubtitleGroupService.save(eleSourceSubtitleGroup);
		
		EleSourceGroup eleSourceGroup = new EleSourceGroup();
		eleSourceGroup.setName(eleSourceSubtitleGroup.getName());
		eleSourceGroup.setVisible("0");
		eleSourceGroup.setType("subtitle");
		boolean noNeedCheck = UserUtils.getSubject().isPermitted("source:eleSourceGroup:check")
                || SwitchUtils.isClose("source:eleSourceGroup:check");
		if(noNeedCheck){
			eleSourceGroup.setDelFlag(EleSourceGroup.DEL_FLAG_NORMAL);
		}else{
			eleSourceGroup.setDelFlag(EleSourceGroup.DEL_FLAG_AUDIT);
		}
		
		EleSource source = new EleSource();
		source.setId("");
		source.setType("subtitle");
		source.setName("SubtitleUpload");
		source.setContent(eleSourceSubtitleGroup.getId());
		
		List<EleSource> esList = Lists.newArrayList();
		esList.add(source);
		eleSourceGroup.setEleSourceList(esList);
		System.out.println(JsonMapper.toJsonString((eleSourceSubtitleGroup)));

		eleSourceGroupService.save(eleSourceGroup);
		String basePath = Global.getUserfilesBaseDir();
		try {
			templetService.createPackageForSourceGroup(eleSourceGroup, basePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		eleSourceSubtitleGroupService.updateGroupId(eleSourceGroup.getId(), eleSourceSubtitleGroup.getId());
	}
	public void saveUploadResource(EleSourceMultimedia eleSourceMultimedia) {
		eleSourceMultimediaService.save(eleSourceMultimedia);
		
		EleSourceGroup eleSourceGroup = new EleSourceGroup();
		eleSourceGroup.setName(eleSourceMultimedia.getName());
		eleSourceGroup.setVisible("0");
		eleSourceGroup.setType("multimedia");
		boolean noNeedCheck = UserUtils.getSubject().isPermitted("source:eleSourceGroup:check")
                || SwitchUtils.isClose("source:eleSourceGroup:check");
		if(noNeedCheck){
			eleSourceGroup.setDelFlag(EleSourceGroup.DEL_FLAG_NORMAL);
		}else{
			eleSourceGroup.setDelFlag(EleSourceGroup.DEL_FLAG_AUDIT);
		}
		
		
		EleSource source = new EleSource();
		source.setId("");
		source.setType("multimedia");
		source.setName("MultimediaUpload");
		source.setContent(eleSourceMultimedia.getId());
		
		List<EleSource> esList = Lists.newArrayList();
		esList.add(source);
		eleSourceGroup.setEleSourceList(esList);
		System.out.println(JsonMapper.toJsonString((eleSourceMultimedia)));

		
		eleSourceGroupService.save(eleSourceGroup);
		String basePath = Global.getUserfilesBaseDir();
		try {
			templetService.createPackageForSourceGroup(eleSourceGroup, basePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		eleSourceMultimediaService.updateGroupId(eleSourceGroup.getId(), eleSourceMultimedia.getId());
	}
}
